package com.sunbim.rsrv.controller.v1;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunbim.rsrv.common.response.R;
import com.sunbim.rsrv.common.validation.StrNoEmpty;
import com.sunbim.rsrv.params.user.*;
import com.sunbim.rsrv.pojo.User;
import com.sunbim.rsrv.service.StorageService;
import com.sunbim.rsrv.service.UserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yuhui
 * @since 2021-12-30
 */
@Api(tags = "用户") // swagger
@Slf4j  // 日志
@Validated // 参数校验

@RestController
@RequestMapping("/api/v1/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StorageService storageService;

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody @Valid UserLoginParams userLoginParams) {
        return userService.login(userLoginParams);
    }

    @ApiOperation(value = "注册用户", notes = "需要管理员权限")
    @SaCheckRole("admin")
    @PostMapping("register")
    public String regist(
//            @ApiParam(value = "id", required = false)
//            @RequestParam(value = "id", required = true) Integer id,

            @NotBlank(message = "用户名不能为空")
            @ApiParam(value = "用户名", required = true)
            @RequestParam(value = "username", required = true) String username,

            @NotBlank(message = "密码不能为空")
            @ApiParam(value = "密码", required = true)
            @RequestParam(value = "password", required = true) String password,

            @ApiParam(value = "昵称", required = false)
            @RequestParam(value = "nickname", required = false) String nickname,

            @NotBlank(message = "区域不能为空")
            @ApiParam(value = "区域", required = true)
            @RequestParam(value = "region", required = true) String region,

            @NotNull(message = "区域等级不能为空")
            @ApiParam(value = "区域等级", required = true)
            @RequestParam(value = "region_level", required = true) Integer regionLevel,

            @ApiParam(value = "用户角色", required = false)
            @RequestParam(value = "role", required = false) String userRole,

            @StrNoEmpty(message = "项目名称不能为空")
            @ApiParam(value = "项目名称", required = false)
            @RequestParam(value = "project_name", required = false) String projectName,

            @ApiParam(value = "项目描述", required = false)
            @RequestParam(value = "project_desc", required = false) String projectDesc,

            @ApiParam(value = "项目坐标,字符串格式:\"lng,lat\"", required = false)
            @RequestParam(value = "geo", required = false) String projectGeo,

            @ApiParam(value = "项目封面")
            @RequestPart(value = "file", required = false) MultipartFile file
    ) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setUserRole(userRole);
        user.setRegion(region);
        user.setRegionLevel(regionLevel);
        user.setProjectDesc(projectDesc);
        user.setProjectName(projectName);
        user.setProjectGeo(projectGeo);
//        if (ObjectUtil.isNotNull(id)) {
//            user.setId(id);
//            userService.updateUser(user);
//            storageService.upload(null, id, null, "icon", "", file);
//            return "更新成功";
//        }
        userService.register(user, file);
        return "注册成功";
    }

    @ApiOperation(value = "更新用户", notes = "需要管理员权限")
    @SaCheckRole("admin")
    @PostMapping("update")
    public String update(@Validated @ModelAttribute UserUpdateParams userUpdateParams){
        userService.updateUser(userUpdateParams.toUser(), userUpdateParams.getFile());
        return "更新成功";

    }

    @ApiOperation(value = "退出登录")
    @GetMapping("logout")
    public String logout() {
        userService.logout();
        return "退出成功";
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("changePassword")
    public String changePassword(@RequestBody @Valid UserChangePasswordParams params) {
        userService.changePassword(params);
        return "密码更新成功";
    }

    @ApiOperation(value = "分页查询全部用户", notes = "1.需要管理员权限<br/>2.不查询管理员<br/>3.若pageSize=0或没有传pageSize则不进行分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @SaCheckRole("admin")
    @GetMapping("selectAll")
    public PageInfo<Map<String, Object>> findAllExcludeAdmin(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") Integer pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> userList = userService.getAllExcludeAdmin();
        return PageInfo.of(userList);
    }

    @ApiOperation(value = "根据id查询一个用户的信息")
    @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", dataTypeClass = int.class, required = true)
    @SaCheckRole("admin")
    @GetMapping("selectOneById")
    public Map<String, Object> selectOneById(
            @RequestParam(value = "id") Integer userId
    ) {
        return userService.getUserById(userId);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("getLoginUser")
    public Map<String, Object> getLoginUser() {
        Object loginId = StpUtil.getLoginId();
        return userService.getUserById(loginId);
    }

    @ApiOperation(value = "根据项目名称模糊查询用户列表")
    @ApiImplicitParam(paramType = "query", name = "keyword", value = "项目的名称关键字", dataTypeClass = String.class, required = true)
    @GetMapping("searchByProjectName")
    public List<Map<String, Object>> searchByProjectName(
            @RequestParam(value = "keyword") String keyword
    ) {
        return userService.searchByProjectName(keyword);
    }

    @ApiOperation(value = "删除一个用户")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户id", dataTypeClass = int.class, required = true)
    @SaCheckRole("admin")
    @GetMapping("delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userService.deleteUser(id);
        return "用户删除成功";
    }
}

